/*
 *
 */
package com.hanhai.zrb.backend.admin.service.impl;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;

import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.hanhai.zrb.backend.admin.dao.mybatis.BackUserRoleDao;
import com.hanhai.zrb.backend.admin.dao.mybatis.RoleDao;
import com.hanhai.zrb.backend.admin.dao.mybatis.RolePrivilegeDao;
import com.hanhai.zrb.backend.admin.model.dto.RoleDto;
import com.hanhai.zrb.backend.admin.service.RoleService;

@Service("roleService")
public class RoleServiceImpl implements RoleService {

	@Resource
	private RoleDao roleDao;

	@Resource
	private BackUserRoleDao backUserRoleDao;

	@Resource
	private RolePrivilegeDao rolePrivilegeDao;

	@Override
	@Transactional
	public void add(RoleDto role) {
		roleDao.add(role);
		addPrivileges(role);
	}

	private void addPrivileges(RoleDto role) {
		Integer roleId = role.getId();
		String[] privileges = role.getPrivilegeArray();
		if (privileges != null) {
			for (String acl : privileges) {
				if (StringUtils.isNotBlank(acl)) {
					Map<String, Object> params = new HashMap<String, Object>();
					params.put("role_id", roleId);
					params.put("acl", acl);
					rolePrivilegeDao.add(params);
				}
			}
		}
	}

	@Override
	@Transactional
	public void update(RoleDto role) {
		roleDao.update(role);
		Integer roleId = role.getId();
		// 先删除已有的权限
		rolePrivilegeDao.deleteByRole(roleId);
		addPrivileges(role);
	}

	@Override
	public List<Map<String, Object>> listAll() {
		return roleDao.listAll();
	}

	@Override
	public Map<String, Object> get(Integer id) {
		return roleDao.get(id);
	}

	@Override
	public Map<String, Object> getDetail(Integer id) {
		return roleDao.get(id);
	}

	@Override
	@Transactional
	public boolean delete(Integer id) {
		boolean succeed = false;
		List<Map<String, Object>> list = backUserRoleDao.getByRole(id);
		if (list == null || list.size() == 0) {
			roleDao.delete(id);
			succeed = true;
		}
		return succeed;
	}

}
